var CountdownButton = function () {
  var template = /* html */ `
    <el-button :style="btnStyle"  class="countdown-button" :type="type" :size="size"
      :disabled="loading" @click="toAction">
      <span v-if="btnCount===0">{{text}}</span>
      <span v-else>{{actionText||text}}({{btnCount}})</span>
    </el-button>
  `;

  return {
    props: {
      width: String,
      text: String,
      actionText: String,
      beforeClickFun: Function,
      count: {
        type: Number,
        default: 5
      },
      type: String,
      size: String
    },

    computed: {
      btnStyle: function () {
        var style = {
          padding:'12px 0'
        };
        var width = this.width;
        if (width !== undefined) {
          style.width = width;
        }
        return style;
      }
    },

    data: function () {
      return {
        loading: false,
        timer: null,
        btnCount: 0
      };
    },

    beforeDestroy: function () {
      this.clearCountRun();
    },

    methods: {
      toAction: function () {
        var beforeClickFun = this.beforeClickFun;
        if (beforeClickFun === undefined) {
          this.loading = true;
          this.toRunTimer();
          return;
        }

        this.loading = true;
        var self = this;
        beforeClickFun().then(function(flag){
          if (flag) {
            self.toRunTimer();
          } else {
            self.loading = false;
          }
        }).catch(function(){
          self.loading = false;
        });
      },

      toRunTimer: function () {
        this.clearCountRun();

        var self = this;
        this.btnCount = this.count;
        this.timer = setInterval(function () {
          var btnCount = self.btnCount;
          btnCount--;
          self.btnCount = btnCount;
          if (btnCount === 0) {
            self.clearCountRun();
            self.loading = false;
          }
        }, 1000);
      },

      clearCountRun: function () {
        var timer = this.timer;
        if (timer !== null) {
          clearInterval(timer);
        }
        this.$emit('click');
      },

      resetBtn:function(){
        this.clearCountRun();
        this.loading = false;
        this.btnCount = 0;
      }
    },

    template: template
  };
}();